from web_api import *
from model import *
'''
provides ui interfaces for the application
'''

ws = webServer()
template = templateFactory()

class meetingBase(object):
    '''
    Base class for other meeting methods
    '''

    def __init__(self):
        '''
        Log user information
        '''
        ws.log('did this happen first??? ')


       
    """
    @cherrypy.expose
    def createEvent(self, ):
        '''
        Create a new event in the database...
        '''
        
        userID = ws.getSessionValue('UID')
        
    """    
    
    @cherrypy.expose
    def doLogout(self):
        '''
        Clear session
        Logout user
        '''
        ws.logout()
    @cherrypy.expose   
    def goToMain(self):
        '''
        Return to main page
        '''
        ws.redirect()
        
    @cherrypy.expose
    def createEvent(self, **FormData ):
        '''
        Handler for schedule.html form -> createEventForm
        '''
        FormData['HOST_ID'] = ws.getSessionValue('UID')
        
        print "Got this -> %s" %(FormData)
        cc = calendarControl()
        cc.addEvent(FormData)
        ws.redirect()
    


class eventServices(meetingBase):
    
    
    def __init__(self):
        self.ec = eventControl()
    
    def __getEventData(self, mid):
        '''
        Event Details
        '''

        _Data = self.ec.getEventById(mid)
        _Data['UID'] = ws.getSessionValue('UID')
        _Data['sess_fullname'] = ws.getSessionValue('FullName')
        return _Data
    
    
    @cherrypy.expose
    def eventDetail(self, EventId ):
        '''
        display panel for event
        features include:
        1.) Display event details
        2.) Edit Event 
        3.) Cancel Event (Only for future events...)
        '''
        """
        ec = eventControl()
        eventData = ec.getEventById(mid)
        
        '''
        Event Data -> {'Attendees': [
        {'listName': u'UserName', 'statusDesc': u'Invited', 'userID': 2, 'statusID': 0}, 
        {'listName': u'UserName', 'statusDesc': u'Invited', 'userID': 3, 'statusID': 0}], 
        'Event': {
        'hostid': 1, 
        'end': 1312203600, 
        'room': u'GrandHall', 
        'eventStatusDesc': u'Scheduled', 
        'title': u'sadfa',
        'eventStatusID': 1, 
        'start': 1312200000, 
        'roomSize': 200}
        }

        '''
        eventData['sess_fullname'] = ws.getSessionValue('FullName')
        #print "Got this Request -> %s" %(mid)
        #userFullName = ws.getSessionValue('FullName')
        #data = {'sess_fullname': userFullName, }
        """
        
        eventData = self.__getEventData(EventId)
        
        #uid = ws.getSessionValue('UID')
        
        thisEvent = eventData['Event']
        if (int(thisEvent['hostid']) == int(eventData['UID'])):
            eventData['_CORD_'] = 'coordinator'
            
            
        print "Event -> %s" %(eventData)
        return  template.render('main_event.html', eventData)
    
    """
    @cherrypy.expose
    def eventNotice(self, EventId):
        '''
        Publish the event details
        Allow user to respond with yes or no to the invite
        '''
        eventData = self.__getEventData(EventId)
        eventData['_INVITE_'] = 'invite'
        
        return  template.render('main_event.html', eventData)
    """    
        
        
        

class adminControls(meetingBase):
    
    
    '''
    Admin specifc features
    Has CRUD rights for:
    1.) Rooms
    2.) Users
    
    '''
    
    def __init__(self):
        '''
        Load admin module from model
        '''
        self.ac = adminControl()
    
    @cherrypy.expose
    def userAddWs(self, **formData):
        '''
        Add user to the system 
        '''
        print "Got from form -> %s" %(formData)
        try:
            result = self.ac.userAdd(formData)
            return result
        except:
            '''
            If there is a problem with the submitted data
            then return a fail condition to the web service
            '''
            return 'Failed'
       
    
    
    @cherrypy.expose
    def userDelWs(self, **formData):
        '''
        Delete a user from the system 
        This action includes removing:
        1.) User data
        2.) All Events
        3.) All Attended events 
        '''
        #print "Got from form -> %s" %(formData)
        result = self.ac.userDel(formData['delUserId'])
        
        return result
    
    @cherrypy.expose
    def userModWs(self, **formData):
        '''
        '''
        try:
           
            if (not formData.has_key('IsAdmin')): 
                formData['IsAdmin'] = 0
            print "Got from form -> %s" %(formData)
            result = self.ac.userMod(formData)
            return result
        except:
            return 'Failed'
    
    @cherrypy.expose
    def roomAddWs(self, **formData):
        '''
        Add a new room to system
        '''
        #print "Got from form -> %s" %(formData)
        try:
            result = self.ac.roomAdd(formData)
            return result
        except:
            '''
            If there is a problem with the submitted data
            then return a fail condition to the web service
            '''
            return 'Failed'
    
    @cherrypy.expose
    def roomModWs(self, **formData):
        '''
        '''
        try: 
            result = self.ac.roomMod(formData)
            return result
        except:
            return 'Failed'
        
    
    

class webServices(meetingBase):
    '''
    Web services for application
    '''
    
    
    def __init__(self):
        # Load Controls

        self.rc = roomControl()
        self.cc = calendarControl()
        self.uc = userControl()
        self.mc = mailControl()
        
        
    
    @cherrypy.expose
    def getRoomData(self):
        '''
        Accessable via /ws/getRoomData
        '''
        '''
        #Tests 
        jsonTest = """ [{"roomName": "RoomA", "roomID": 1, "roomSize": 10}, {"roomName": "RoomB", "roomID": 2, "roomSize": 3}, {"roomName": "RoomC", "roomID": 3, "roomSize": 20}, {"roomName": "RoomD", "roomID": 4, "roomSize": 15}, {"roomName": "RoomE", "roomID": 5, "roomSize": 8}] """
        return jsonTest
        '''
        
        rooms = self.rc.getWsRoomList()
        return rooms
    
    @cherrypy.expose
    def getEventById(self, EventID):
        '''
        Return event data
        '''
        print "--- Calling getEventById"
        event = self.cc.getWsEventById(EventID)
        return event
    
    @cherrypy.expose
    def getRoomById(self, rid):
        '''
        Get room data by id
        '''

        
        rooms = self.rc.getWsRoomById(rid)
        return rooms
    
    @cherrypy.expose
    def getUserData(self):
        '''
        Accessable via /ws/getUserData
        '''
        return  self.uc.getWsEventUsers(ws.getSessionValue('UID'))
    
    
    
    @cherrypy.expose
    def getUserNameById(self, uid, getFullName=None, format='python'):
        '''
        return user information given a user id
        '''
        return self.uc.getUserById(uid, getFullName, format)
        
    
    @cherrypy.expose
    def getEventData(self, start, end, _):
        '''
        Accessable via /ws/getUserData
        '''
        
        return self.cc.getWsEventList(ws.getSessionValue('UID'))
    
    @cherrypy.expose
    def getAllEventData(self):
        '''
        Accessable via /ws/getUserData
        '''

        return self.cc.getWsEventList(ws.getSessionValue('UID'))
    

    @cherrypy.expose
    def eventCancel(self, **formData):
        '''
        Cancel an event in the database
        '''
        self.mc.sendMail(formData['email'], formData['title'], formData['EventID'], type='cancel')
        return self.cc.doCancelEvent(formData)
    
    @cherrypy.expose
    def eventAccept(self, **formData):
        '''
        Accept a meeting invite
        '''

        return self.cc.doAcceptEvent(formData)
    
    @cherrypy.expose
    def eventDecline(self, **formData):
        '''
        Cancel a meeting invite
        '''

        return self.cc.doDeclineEvent(formData)

    @cherrypy.expose
    def checkConflicts(self, **formData):
        '''
        Check for Conflicts
        '''
        print "Got this from the form -> %s" %(formData)
        return self.cc.checkForConflicts(formData, ws.getSessionValue('UID'))
        #return self.cc.checkForConflicts(formData)
    
    @cherrypy.expose
    def getEvents(self, **eReq):
        '''
        Publish event requests
        '''
        return self.cc.getWsCurrentEvents( ws.getSessionValue('UID'))
    
    
    @cherrypy.expose
    def updateEvent(self, **eReq):
        '''
        Publish event requests
        Event Update {'eventStrtTimeMer': u'p', 
        'eventStrtTimeHr': u'9', 
        'eventStrt': u'09/30/2011', 
        'eventDurationMin': u'0', 'selRoom': u'14', 
        'eventStrtTimeMin': u'00', 'selUser': [u'2', u'3'], 
        'eventDesc': u'Finish Paper', 
        'eventDurationHr': u'1', 
        'formEventID': u'80'}
        '''
        print "Event Update %s" %(eReq)
        return self.cc.updateEvent(eReq)    
    
    """
    @cherrypy.expose
    def sendNotification(self, **eReq):
        '''
        Send Email notifications
        '''
        print "SENDING NOTIFICATION -------------------------------------------"
        print "Got This -> %s" %(eReq)
        return self.mc.sendMail(eReq['email'], eReq['title'], eReq['eventID'], 'cancel')
    """

class meetingController(meetingBase):
    
    
    def __init__(self):
        '''
        Load additional web parts into the controller view
        '''
        self.ws =  webServices()
        self.event = eventServices()
    
    def handle_error():
        cherrypy.response.status = 500
        cherrypy.response.body = ["<html><body>Sorry, an error occured</body></html>"]
    
    
        
    @cherrypy.expose
    def index(self):
        '''
        This is the main page...
        '''
        info = {}
        data = {}
        
        timeout = cherrypy.session
        info['addr'] = cherrypy.request.remote.ip
        info['port'] = cherrypy.request.remote.port
        info['host'] = cherrypy.request.remote.name
        
        '''
        Get full name set during login...
        '''
        
        userFullName = ws.getSessionValue('FullName')
        adminCheck = ws.getSessionValue('isAdmin')
        if int(adminCheck) == 1:
            '''
            Load the admin controls
            Only admins can perform administration actions.
            '''
            print "[MAIN] Enabling Admin controls..."
            self.admin = adminControls()
        
        
        
        print "Dump session values...."
        for (k,v) in ws.dumpSession():
            print "%s = %s" %(k, v)
        data = {'sess_fullname': userFullName, 'sess_admin': adminCheck, 'name': 'State_Your_Name', 'to': timeout, 'data': [{'this': 'a', 'that': '1'}, {'this': 'b', 'that': '2'},{'this': 'c', 'that': '3'} ] }
        return  template.render('main.html', data)
    
       






